package com.ndp.fb.walle.business.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.rdb.api.EcColorTypeRdbService;
import com.ndp.fb.rdb.api.EcElementAttachRdbService;
import com.ndp.fb.rdb.api.EcElementStyleRdbService;
import com.ndp.fb.rdb.api.EcTemplateElementRdbService;
import com.ndp.fb.rdb.model.EcMaterielCategory;
import com.ndp.fb.rdb.model.EcTemplateElement;
import com.ndp.fb.rdb.model.Pager;
import com.ndp.fb.rdb.model.User;
import com.ndp.fb.rdb.model.ecelement.EcElementAttach;
import com.ndp.fb.rdb.model.ectemplate.EcColorType;
import com.ndp.fb.rdb.model.ectemplate.EcElementStyle;
import com.ndp.fb.storage.StorageService;
import com.ndp.fb.util.ListUtil;
import com.ndp.fb.util.StringUtil;
import com.ndp.fb.walle.business.EcElementService;
import com.ndp.fb.walle.business.TemplateService;
import com.ndp.fb.walle.util.FileUploadUtils;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by evan on 2016/7/8.
 */
@Component
public class EcElementServiceImpl implements EcElementService {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    StorageService storageService;

    @Autowired
    TemplateService templateService;

    @Reference
    EcElementAttachRdbService ecElementAttachRdbService;

    @Reference
    EcTemplateElementRdbService ecTemplateElementRdbService;

    @Reference
    EcColorTypeRdbService ecColorTypeRdbService;

    @Reference
    EcElementStyleRdbService ecElementStyleRdbService;

    @Override
    public List<EcElementAttach> findByType(Long orgId, Integer type) {
        return ecElementAttachRdbService.findByType(orgId, type);
    }

    @Override
    public void parse(User user, Long templateId, String folder) throws Exception{
        List<EcElementStyle> ecElementStyles = ecElementStyleRdbService.findAll();
        List<EcColorType> ecColorTypes = ecColorTypeRdbService.findAll();
        Map<String, Long> ecElementStyleMap = ecElementStyles.stream().filter(i -> StringUtil.isNotEmpty(i.getCode())).collect(Collectors.toMap(EcElementStyle::getCode, EcElementStyle::getId));
        Map<String, Long> ecColorTypeMap = ecColorTypes.stream().filter(i -> StringUtil.isNotEmpty(i.getName())).collect(Collectors.toMap(EcColorType::getName, EcColorType::getId));

        File file = new File(folder);
        List<EcTemplateElement> ecTemplateElementList = new ArrayList<>();
        templateService.parseElement(templateId, user, ecTemplateElementList, file, ecElementStyleMap, ecColorTypeMap, null);
        //批量保存元素
        if(ListUtil.isNotEmpty(ecTemplateElementList))
            ecTemplateElementRdbService.batchSave(ecTemplateElementList);
    }

    @Override
    public EcElementAttach insert(User user, String filename, File elementAttachFile) throws Exception {
        Integer type;

        String eleAttachCode = FileUploadUtils.getFileNameNoEx(filename).toUpperCase();
        if(eleAttachCode.startsWith("BG01"))
            type = 1;
        else if (eleAttachCode.startsWith("BG02"))
            type = 2;
        else if (eleAttachCode.startsWith("BK"))
            type = 3;
        else
            return null;
        String[] eleAttachCodeArr = eleAttachCode.split(CommonConstants.SYMBOL_UNDERLINE);
        EcElementAttach ecElementAttach;
        if(eleAttachCodeArr.length >= 2)
            ecElementAttach = ecElementAttachRdbService.findByCodeAndType(eleAttachCodeArr[0], eleAttachCodeArr[1], type, user.getOrgId());
        else
            ecElementAttach = ecElementAttachRdbService.findByCodeAndType(eleAttachCodeArr[0], null, type, user.getOrgId());

        /**
         * 根据传入的文件名  传过就覆盖
         * 没传过 插入设计元素
         */
        String desginElementS3Url;
        try {
            desginElementS3Url = storageService.storeElementAsPublic("bg", elementAttachFile, System.currentTimeMillis() + filename);
        } catch (IOException e) {
            desginElementS3Url = storageService.storeElementAsPublic("bg", elementAttachFile, System.currentTimeMillis() + filename);
        }
        if(ecElementAttach == null) {
            ecElementAttach = new EcElementAttach();
            ecElementAttach.setCreateTime(new Date().getTime());
            ecElementAttach.setUserId(user.getTicket());
            ecElementAttach.setOrgId(user.getOrgId());
            ecElementAttach.setIsDelete(0);
            ecElementAttach.setAttachElementType(type);
            ecElementAttach.setAttachElementName(filename);
            ecElementAttach.setAttachElementCode1(eleAttachCodeArr[0]);
            if(eleAttachCodeArr.length >= 2)
                ecElementAttach.setAttachElementCode2(eleAttachCodeArr[1]);
            ecElementAttach.setAttachElementImg(desginElementS3Url);

            return ecElementAttachRdbService.save(ecElementAttach);
        } else {
            ecElementAttach.setIsDelete(0);
            ecElementAttach.setAttachElementImg(desginElementS3Url);
            ecElementAttachRdbService.update(ecElementAttach);
            return ecElementAttach;
        }
    }

    @Override
    public Pager<EcElementAttach> getAllDesignEle(Long orgId, Integer type, Integer firstResult, Integer sizeNo) {
        return ecElementAttachRdbService.getAllDesignEle(orgId, type, firstResult, sizeNo);
    }

    @Override
    public List<EcElementAttach> getAllAttach(Long orgId) {
        return ecElementAttachRdbService.findByOrgId(orgId);
    }
}
